package fti.uksw.ruang;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import fti.uksw.ruang.dialog.YesNoDialog;
import fti.uksw.ruang.model.CalendarEvent;
import fti.uksw.ruang.model.Login;
import fti.uksw.ruang.model.MsgCode;
import fti.uksw.ruang.model.RecurringDetail;
import fti.uksw.ruang.websocket.ClientListener;
import fti.uksw.ruang.websocket.WebSocketClient;

//import android.support.v4.app.ListFragment;

public class ListKegActivity<listKegClick> extends ActionBarActivity implements
		ClientListener {

	private final String TAG = ListKegActivity.class.getName();

	private ListView lv;

	private AdapterListKeg adapterListKeg;
	private ArrayList<CalendarEvent> listEvent;

	private WebSocketClient wsClient = LoginActivity.wsClient;

	private Login login;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.keg_listview);

		lv = (ListView) findViewById(R.id.lv_keglistview);

		login = (Login) getIntent().getExtras().get(Login.TAG);

		listEvent = getIntent().getParcelableArrayListExtra(CalendarEvent.TAG);
		adapterListKeg = new AdapterListKeg(this, listEvent);
		lv.setAdapter(adapterListKeg);
		lv.setOnItemClickListener(listKegClick);

		wsClient.addListener(this);

		ActionBar ab = getSupportActionBar();
		ab.setTitle("List Event");
	}

	private CalendarEvent event;

	private OnItemClickListener listKegClick = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> adapter, View v, int position,
				long id) {
			Intent intNewItem = new Intent(getApplicationContext(),
					NewItemAct.class);
			CalendarEvent ce = (CalendarEvent) adapter
					.getItemAtPosition(position);
			intNewItem.putExtra(NewItemAct.TAG_EDIT_EVENT, true);
			intNewItem.putExtra(Login.TAG, login);
			intNewItem.putExtra(CalendarEvent.TAG, ce);
			startActivity(intNewItem);
			finish();

			// event = (CalendarEvent) lv.getAdapter().getItem(position);
			//
			// YesNoDialog yesNoDialog = YesNoDialog.newInstance(
			// getApplicationContext(), "Delete Event", "Are you sure?");
			// yesNoDialog
			// .setYesNoDialogListener(new YesNoDialog.YesNoDialogListener() {
			//
			// @Override
			// public void yesListener() {
			// JSONObject msg = new JSONObject();
			// try {
			// msg.put(MsgCode.MSGCODE, MsgCode.DELEVENTREQ);
			// msg.put(CalendarEvent.RECURRINGRULE,
			// event.getRecurringRule());
			// msg.put(CalendarEvent.ID, event.getId());
			// msg.put(Login.USERNAME, login.getUsername());
			// Log.d(TAG, msg.toString());
			// wsClient.sendTextMessage(msg.toString());
			// // Intent intentCalView = new Intent(
			// // getApplicationContext(),
			// // CalViewAct.class);
			// // intentCalView.putExtra(Login.TAG, login);
			// // startActivity(intentCalView);
			// // finish();
			// } catch (JSONException e) {
			// e.printStackTrace();
			// }
			// }
			//
			// @Override
			// public void noListener() {
			// }
			// });
			// yesNoDialog.show(getSupportFragmentManager(), "yesnodialog");
		}
	};

	@Override
	public void onConnect(String message) {

	}

	@Override
	public void onMessage(String message) {
		Log.d(TAG, message);
		try {
			JSONObject msg = new JSONObject(message);
			String msgCode = msg.getString(MsgCode.MSGCODE);
			if (msgCode.equals(MsgCode.MSGCONFIRM)) {
				Toast.makeText(getApplicationContext(),
						msg.getString(MsgCode.MSGCONTENT), Toast.LENGTH_LONG)
						.show();

				adapterListKeg.removeKeg(event);
				adapterListKeg.notifyDataSetChanged();

			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void onMessage(byte[] data) {

	}

	@Override
	public void onDisconnect(String reason) {
		Toast.makeText(this, "Disconnect from server", Toast.LENGTH_LONG)
				.show();
		logout(getIntent(),
				getWindow().getDecorView().findViewById(android.R.id.content));
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (wsClient.isConnected()) {
			Log.d(TAG, "remove clientlistener");
			wsClient.removeListener(this);
		}
	}

	private void logout(Intent i, View v) {
		wsClient.removeListener(this);
		wsClient.closeConnection();
		i = new Intent(v.getContext(), LoginActivity.class);
		v.getContext().startActivity(i);
		finish();
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			wsClient.removeListener(this);
			Intent intentCalView = new Intent(getApplicationContext(),
					CalViewAct.class);
			intentCalView.putExtra(Login.TAG, login);
			startActivity(intentCalView);
			finish();
		}
		return super.onKeyDown(keyCode, event);
	}

	@Override
	public void onError(Exception error) {

	}

	public class AdapterListKeg extends BaseAdapter {

		private Activity a;
		private List<CalendarEvent> list;
		private LayoutInflater inflater = null;

		public AdapterListKeg(Activity mA, List<CalendarEvent> mList) {
			a = mA;
			inflater = (LayoutInflater) a
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			list = mList;
		}

		public void removeKeg(CalendarEvent ce) {
			list.remove(ce);
		}

		@Override
		public int getCount() {
			return list.size();
		}

		@Override
		public Object getItem(int arg0) {
			return list.get(arg0);
		}

		@Override
		public long getItemId(int position) {
			return list.get(position).getId();
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			if (convertView == null) {
				convertView = inflater.inflate(R.layout.keg_listview_adapter,
						null);
			}
			CalendarEvent ce = (CalendarEvent) list.get(position);

			TextView tvEventName = (TextView) convertView
					.findViewById(R.id.tv_keglv_kegname);
			TextView tvRoomName = (TextView) convertView
					.findViewById(R.id.tv_keglv_roomname);
			TextView tvStartDate = (TextView) convertView
					.findViewById(R.id.tv_keglv_startdate);
			TextView tvEndDate = (TextView) convertView
					.findViewById(R.id.tv_keglv_enddate);
			TextView tvRepeatUntil = (TextView) convertView
					.findViewById(R.id.tv_keglv_repeatuntil);
			TextView tvDosen = (TextView) convertView
					.findViewById(R.id.tv_keglv_dosen);
			TextView tvPengguna = (TextView) convertView
					.findViewById(R.id.tv_keglv_pengguna);
			Button btnDel = (Button) convertView
					.findViewById(R.id.btn_keglv_del);

			tvEventName.setText(ce.getSubject());
			tvRoomName.setText(ce.getCalendarList().getCalendarTitle());

			SimpleDateFormat sdf = new SimpleDateFormat(
					"E, MMM dd, yyyy hh:mm a");
			Calendar cStart = Calendar.getInstance();
			cStart.setTime(ce.getStartTime());
			Calendar cEnd = Calendar.getInstance();
			cEnd.setTime(ce.getEndTime());

			tvStartDate.setText("From\t\t: " + sdf.format(cStart.getTime()));
			tvEndDate.setText("To\t\t\t: " + sdf.format(cEnd.getTime()));
			if (ce.getRecurringRule() == CalendarEvent.FLAG
					|| ce.getRecurringRule() != CalendarEvent.UNFLAG) {

				RecurringDetail rd = ce.getRecurringDetail();
				Calendar calRd = Calendar.getInstance();
				calRd.setTime(ce.getRecurringDetail().getUntil());

				sdf = new SimpleDateFormat("E, MMM dd, yyyy hh:mm a");
				tvRepeatUntil.setText("Repeat " + rd.getType() + " until "
						+ sdf.format(calRd.getTimeInMillis()));
			} else {
				tvRepeatUntil.setText("No Repeat");
			}

			tvDosen.setText("Dosen\t\t: " + ce.getGuest().getDosen().getNama()
					+ "/" + ce.getGuest().getDosen().getNotelp());
			tvPengguna.setText("Pengguna\t: " + ce.getPengguna().getNama()
					+ "/" + ce.getPengguna().getNoTelp());

			final CalendarEvent _ce = ce;

			btnDel.setOnClickListener(new View.OnClickListener() {

				@Override
				public void onClick(View v) {
					YesNoDialog yesNoDialog = YesNoDialog.newInstance(
							getApplicationContext(), "Delete Event",
							"Are you sure to delete event " + _ce.getSubject()
									+ "?");
					yesNoDialog
							.setYesNoDialogListener(new YesNoDialog.YesNoDialogListener() {

								@Override
								public void yesListener() {
									JSONObject msg = new JSONObject();
									try {
										msg.put(MsgCode.MSGCODE,
												MsgCode.DELEVENTREQ);
										msg.put(CalendarEvent.RECURRINGRULE,
												_ce.getRecurringRule());
										msg.put(CalendarEvent.ID, _ce.getId());
										msg.put(Login.USERNAME,
												login.getUsername());
										Log.d(TAG, msg.toString());
										removeKeg(_ce);
										wsClient.sendTextMessage(msg.toString());
									} catch (JSONException e) {
										e.printStackTrace();
									}
								}

								@Override
								public void noListener() {
								}
							});
					yesNoDialog
							.show(getSupportFragmentManager(), "yesnodialog");
				}
			});

			return convertView;
		}

	}

}
